package com.zhanggm.zyk.contract.controller;


import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhanggm.zyk.contract.config.AjaxResult;
import com.zhanggm.zyk.contract.entity.TContracts;
import com.zhanggm.zyk.contract.feign.AuthService;
import com.zhanggm.zyk.contract.feign.TUser;
import com.zhanggm.zyk.contract.service.ITContractsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhanggm
 * @since 2024-05-24
 */
@RestController
@RequestMapping("/contracts")
public class TContractsController {

    @Autowired
    ITContractsService itContractsService;

    @Autowired
    AuthService authService;

    @Autowired
    HttpServletRequest request;


    @GetMapping("page")
    public Object page(TContracts contracts,Integer pageNum,Integer pageSize) {
        //获取
        Object userId = JWTUtil.parseToken(request.getHeader("token")).getPayload("id");
        //封装查询条件
        LambdaQueryWrapper<TContracts> queryWrapper = new LambdaQueryWrapper<>();
        //查询用户自己的合同
        queryWrapper.eq(TContracts::getUserId, userId);
        //其它查询条件 等等
        if (contracts.getContractNumber() != null) {
            queryWrapper.eq(TContracts::getContractNumber, contracts.getContractNumber());
        }
        PageHelper.startPage(pageNum, pageSize);
        List<TContracts> list = itContractsService.list(queryWrapper);
        return list;

    }

    @PostMapping("save")
    public Object save(TContracts tContracts) {
        //根据token拿到用户id或用户名称
        Object userId = JWTUtil.parseToken(request.getHeader("token")).getPayload("id");
        //校验用户是否是房东
        TUser user = authService.getUserById(Integer.valueOf(userId+""));
        if (!user.getRole().equals("fangdong")) {
            return false;
        }
        tContracts.setUserId(user.getId());

        itContractsService.save(tContracts);

        return AjaxResult.success();
    }

}
